package com.simple.relaxed.anno.impl;

import com.simple.relaxed.anno.Slice;
import com.simple.relaxed.manager.impl.SliceManager;
import com.simple.relaxed.utils.ReflectionsUtil;
import ohos.aafwk.ability.AbilitySlice;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Set;

public class SliceImpl {

    /**
     * 全局扫描被@Slice注解标记的AbilitySlice的类，并且将其注册到SliceManger容器中统一管理
     *
     * @throws NoSuchMethodException     当找不到指定的Method对象时，抛出此异常
     * @throws IllegalAccessException    当实例化对象失败时，抛出此异常
     * @throws InvocationTargetException 反射实例化失败时，抛出此异常
     * @throws InstantiationException    实例化失败时，抛出此异常
     */
    public static void sliceImpl() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Set<Class<?>> classes = ReflectionsUtil.getClassByAnnotationClass(Slice.class);
        if (classes == null || classes.isEmpty()) {
            return;
        }
        Class<AbilitySlice> aClass = AbilitySlice.class;
        for (Class<?> clazz : classes) {
            if (!aClass.isAssignableFrom(clazz)) {
                continue;
            }
            Constructor<?> constructor = clazz.getDeclaredConstructor();
            if (constructor.getParameterCount() != 0) {
                continue;
            }
            AbilitySlice o = (AbilitySlice) constructor.newInstance();
            Slice slice = clazz.getDeclaredAnnotation(Slice.class);
            SliceManager.getInstance().register(slice.bindName(), slice.route(), o);
        }
    }
}
